﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using DateBaseConnectionPool;

namespace TestMySqlConnetPoll
{
    public struct objButton
    {
        public int s_time;   //开始时间
        public int e_time;   //结束时间
    }

    public class ButtenUseTable
    {
        #region 变量定义 按钮使用记录
        
        public List<objDate> TimeList = new List<objDate>(); //浏览的时间列表
        
        //浏览记录，以设备号作为键值
        public Dictionary<string, List<objButton>> ValueList = new Dictionary<string, List<objButton>>();
        public bool Ready_TimeList = false;
        public bool Ready_ValueList = false;
        public int ErrorFlag = 0;

        public void ReadTimeList()
        {
            Ready_TimeList = false;
            ErrorFlag = 0;
            object o = new object();                 
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadTimeList),o);
        }

        public void ReadValueList(objDate obj)
        {
            Ready_ValueList = false;
            ErrorFlag = 0;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadValueList), obj);
        }

        #endregion
        #region 按钮使用记录
        private Mutex keyMutex = new Mutex();
        static private int keykey = 0;
        public bool InsertTableData(objDate date, Int16 ButtonNo, objButton obj)
        {
            bool tmpFlag = false;
            string TableName = "buttonannal";
            if (TableName == "") return tmpFlag;
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    tmpFlag = false;
                }
                        
               
                if (con != null)
                {
                    StringBuilder InsertStatement = new StringBuilder();
                    InsertStatement.Append(string.Format("insert into {0}(year,month,day,dev_no,s_time,e_time) ", TableName));

                    InsertStatement.Append(" values(?year,?month,?day,?dev_no,?s_time,?e_time)");

                    MySqlCommand InsertCommand = new MySqlCommand(InsertStatement.ToString(), con);

                    InsertCommand.Parameters.Add(new MySqlParameter("?year", MySqlDbType.Int32)).Value = date.year;
                    InsertCommand.Parameters.Add(new MySqlParameter("?month", MySqlDbType.Byte)).Value = date.month;
                    InsertCommand.Parameters.Add(new MySqlParameter("?day", MySqlDbType.Byte)).Value = date.day;

                    InsertCommand.Parameters.Add(new MySqlParameter("?dev_no", MySqlDbType.Int16)).Value = ButtonNo;

                    InsertCommand.Parameters.Add(new MySqlParameter("?s_time", MySqlDbType.Int16)).Value = obj.s_time;
                    InsertCommand.Parameters.Add(new MySqlParameter("?e_time", MySqlDbType.Int16)).Value = obj.e_time;

                    try
                    {
                        int k = InsertCommand.ExecuteNonQuery();
                        if (k == 1) tmpFlag = true;        //写入成功
                        else tmpFlag = false;              //写入失败
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                        tmpFlag = false;       //写入失败
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                    }
                }
            }
            return tmpFlag;
        }

        private void ThreadReadTimeList(object o)
        {
            TimeList.Clear();
            string TableName = "ButtonAnnal";
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                        
                if (con != null)
                {
                    StringBuilder SelectStatement = new StringBuilder();
                    SelectStatement.Append(string.Format("select year,month,day  from {0}", TableName));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(SelectStatement.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            objDate t = new objDate();
                            t.year = read.GetInt32(read.GetOrdinal("year"));
                            t.month = read.GetByte(read.GetOrdinal("month"));
                            t.day = read.GetByte(read.GetOrdinal("day"));
                            if (TimeList.Contains(t)) { }
                            else TimeList.Add(t);
                        }
                        read.Close();
                        Ready_TimeList = true;
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 2;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 4;
                    }
                }
                else ErrorFlag = 6;
            }
            else ErrorFlag = 7;
        }

        private void  ThreadReadValueList(object o)
        {
            objDate obj = (objDate)o;
            string TableName = "ButtonAnnal";
            objDate date = obj;
            ValueList.Clear();
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                        
                if (con != null)
                {
                    StringBuilder SelectStatement = new StringBuilder();

                    SelectStatement.Append(string.Format("select dev_no,s_time,e_time  from {0} where year = {1} and month = {2} and day = {3} order by s_time", TableName, date.year, date.month, date.day));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(SelectStatement.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            objButton t = new objButton();
                            Int16 no = read.GetInt16(read.GetOrdinal("dev_no"));
                            t.s_time = read.GetInt32(read.GetOrdinal("s_time"));
                            t.e_time = read.GetInt32(read.GetOrdinal("e_time"));

                            string s = c_Device.GetButtenUseDevName(no);

                            if (ValueList.ContainsKey(s))
                            {
                                ValueList[s].Add(t);
                            }
                            else
                            {
                                List<objButton> k = new List<objButton>();
                                k.Add(t);
                                ValueList.Add(s, k);
                            }
                        }
                        read.Close();
                        Ready_ValueList = true;
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 2;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写错误日志
                        ErrorFlag = 3;
                    }
                }
                else ErrorFlag = 6;
            }
            else ErrorFlag = 7;
        }
        #endregion
    }
}
